﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;

namespace FJASPX.Framwork.Dao
{
    public class Repository
    {
        public ISessionFactory factory { get; set; }
        private ISession activeSession { get; set; }

        public Repository()
            : this(false)
        {

        }

        public Repository(bool openSession)
        {

            if (openSession)
            {
                this.activeSession = NHSessionFactory.Instance.GetCurrentSession();
            }
        }
        /// <summary>
        /// Open a NHibernate session. 
        /// </summary>
        public void OpenSession()
        {
            if (this.activeSession == null || !this.activeSession.IsOpen)
            {
                this.activeSession = this.factory.OpenSession();
            }
            else
            {
                throw new InvalidOperationException("The repository already has an open session");
            }
        }
        /// <summary>
        ///  Flushes the current active NHibernate session. 
        /// </summary>
        public void FlushSession()
        {
            if (this.activeSession != null && this.activeSession.IsOpen)
            {
                this.activeSession.Flush();
            }
        }
        /// <summary>
        ///  Close the active NHibernate session 
        /// </summary>
        public void CloseSession()
        {
            if (this.activeSession != null && this.activeSession.IsOpen)
            {
                this.activeSession.Close();
            }
        }
    }
}
